package com.hj.system.config.security.jwt;

import com.alibaba.fastjson.JSON;
import com.hj.system.config.security.base.UserInfo;
import com.hj.system.utils.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        UserInfo jwtUserDetails = (UserInfo) authentication.getPrincipal();
        String json = JSON.toJSONString(jwtUserDetails);
        long ttlMillis = 60*60*60*1000l;
        String jwtToken = JwtUtils.createJwtToken(json, ttlMillis);
        //签发token
        response.getWriter().write(JSON.toJSONString(ResponseUtil.okContent(jwtToken)));
    }
}
